package impl

import (
	"api-gateway-core/socket/parser"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"strings"
)

type PostRequestParser struct {
}

func (this *PostRequestParser) Parse(request *http.Request) parser.ReqParserRes {
	contentType := getContentType(request)
	switch contentType {
	case "multipart/form-data":
		return parseMultipartFormData(request)
	case "application/x-www-form-urlencoded":
		return parseMultipartFormData(request)
	case "application/json":
		return parseJsonBody(request)
	default:
		return parser.ReqParserRes{
			InfoMap: nil,
			Err:     errors.New("未实现的协议类型 Content-Type：" + contentType),
		}
	}
}

// 获取ContentType
func getContentType(request *http.Request) string {
	contentType := ""
	// 获取Content-Type头部
	contentType = request.Header["Content-Type"][0]
	// 查找分号";"的位置
	idx := strings.Index(contentType, ";")
	if idx > 0 {
		// 如果有分号，返回分号之前的部分
		return contentType[:idx]
	}
	// 如果没有分号，返回整个Content-Type
	return contentType
}

// 解析multipart/form-data请求体
func parseMultipartFormData(request *http.Request) parser.ReqParserRes {
	params := make(map[string]any)
	err := request.ParseMultipartForm(32 << 20) // 32 MB
	if err != nil {
		return parser.ReqParserRes{
			InfoMap: nil,
			Err:     err,
		}
	}
	for key, value := range request.MultipartForm.Value {
		params[key] = value[0]
	}
	return parser.ReqParserRes{
		InfoMap: params,
		Err:     nil,
	}
}

// 解析application/json请求体
func parseJsonBody(request *http.Request) parser.ReqParserRes {
	var params map[string]any
	body, err := io.ReadAll(request.Body)
	if err != nil {
		return parser.ReqParserRes{
			InfoMap: nil,
			Err:     err,
		}
	}
	defer request.Body.Close()
	err = json.Unmarshal(body, &params)
	if err != nil {
		return parser.ReqParserRes{
			InfoMap: nil,
			Err:     err,
		}
	}
	return parser.ReqParserRes{
		InfoMap: params,
		Err:     nil,
	}
}
